# -*- coding: utf-8 -*-
"""
@Time ： 2024/10/25 13:32
@Auth ： 刘佳
@File ：logging_config.py
@IDE ：PyCharm
@Motto:日志记录器
"""
# logging_config.py
import logging
from pathlib import Path
from datetime import datetime

class LogHandler(logging.Handler):
    def __init__(self, signal):
        super().__init__()
        self.signal = signal

    def emit(self, record):
        msg = self.format(record)
        self.signal.emit(msg)  # 通过信号发送消息


def setup_logger(name, log_dir, log_signal=None):
    log_dir = Path(log_dir)
    log_dir.mkdir(parents=True, exist_ok=True)  # 确保日志目录存在

    log_file = log_dir / f"{datetime.now().strftime('%Y-%m-%d')}.log"
    logger = logging.getLogger(name)

    if not logger.hasHandlers():
        logger.setLevel(logging.INFO)
        handler = logging.FileHandler(log_file, encoding='utf-8')
        formatter = logging.Formatter('[%(asctime)s] - %(levelname)s - %(message)s', "%Y-%m-%d %H:%M:%S")
        handler.setFormatter(formatter)
        logger.addHandler(handler)

        if log_signal:
            signal_handler = LogHandler(log_signal)
            signal_handler.setFormatter(formatter)
            logger.addHandler(signal_handler)

    return logger